#include "CanProtolProc.h"

static CanCmdInfo canCmdInfoSets[MAX_CAN_CMD_CNT];

uint8_t RegistCanCommand(eUpdateCmdSet eCmd, CanCmdProcCallback cmdCallback)
{
	uint8_t u8CmdIndex = 0xFF;
	for(uint8_t i = 0; i < MAX_CAN_CMD_CNT; i ++)
	{
		if(canCmdInfoSets[i].eCanCmd == eCanCmdReserved)
		{
			canCmdInfoSets[i].eCanCmd = eCmd;
			canCmdInfoSets[i].cmdCallback = cmdCallback;
			u8CmdIndex = i;
			break;
		}
	}

	return u8CmdIndex;
}

static uint8_t GetCanCmdInfo(eUpdateCmdSet eCmd, CanCmdProcCallback *cmdCallback)
{
	uint8_t u8CmdIndex = 0xFF;
	for(uint8_t i = 0; i < MAX_CAN_CMD_CNT; i ++)
	{
		if(canCmdInfoSets[i].eCanCmd == eCmd || 
				canCmdInfoSets[i].eCanCmd == eCanCmdReserved)
		{
			if(canCmdInfoSets[i].cmdCallback)
				*cmdCallback = canCmdInfoSets[i].cmdCallback;
			
			u8CmdIndex = i;
			break;
		}
	}

	return u8CmdIndex;
}

uint8_t ProcCanData(CanRxFrame canRxFrame)
{
	uint8_t res;
	CanCmdProcCallback cmdCallback;
	eUpdateCmdSet cmdNum = (eUpdateCmdSet)GETCMDBYCANID(canRxFrame.rxHeader.StdId);
	
	if(canRxFrame.rxHeader.IDE == CAN_ID_EXT)
		return 0;
	
	if(GetCanCmdInfo(cmdNum, &cmdCallback) != 0xFF)
	{
		if(cmdCallback)
			res = cmdCallback(canRxFrame.rxData, canRxFrame.rxHeader.DLC);
		else
		{
//			printf("ungregister can command!\n\r");			
		}

	}
	else
	{
		res = 0xFF;
	}
	
	return res;
}
